package com.grao.waterschool.human.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class Base64MultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;

    public Base64MultipartFile(byte[] imgContent, String header) {
        this.imgContent = imgContent;
        this.header = header.split(";")[0];
    }

    @Override
    public String getName() {
        return UUID.randomUUID() + "." + getExtension();
    }

    @Override
    public String getOriginalFilename() {
        return UUID.randomUUID() + "." + getExtension();
    }

    @Override
    public String getContentType() {
        return header; // 直接返回MIME类型，如 "image/jpeg"
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (FileOutputStream out = new FileOutputStream(dest)) {
            out.write(imgContent);
        }
    }

    private String getExtension() {
        return header.split("/")[1];
    }
}
